//
//  SLTabBar.swift
//  Sina15
//
//  Created by 盼 on 16/4/6.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit

class SLTabBar: UITabBar {
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addSubview(plusBtn)
    }

    
    required init?(coder aDecoder: NSCoder) {
        //不支持从storyBoard加载
//        fatalError("init(coder:) has not been implemented")
        
        //支持从storyBoard/xib加载
        super.init(coder: aDecoder)
        addSubview(plusBtn)
    }
    
    //MARK: 设置tabBar的item的frame
    override func layoutSubviews() {
        
        //调用父类方法
        super.layoutSubviews()
        
        let itemW = self.frame.width/5
        let itemH = self.bounds.height
        var index:CGFloat = 0
        
        let rect = CGRect(x: 0, y: 0, width: itemW, height: itemH)
        
        for subview in subviews {
            
//            print(subview)
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置item的偏移
                subview.frame = CGRectOffset(rect, index * itemW, 0)
                
                index++
                
                //中间留出一个item的位置
                if index == 2 {
                    index++
                }
                
            }
        }
        
        //设置按钮frame
//        plusBtn.frame = CGRectMake(2 * itemW, 0, itemW, itemY)
        
        plusBtn.frame = CGRectOffset(rect, 2 * itemW, 0)
        
        //设置加号按钮的偏移
//        plusBtn.frame = CGRectOffset(rect, 2 * itemW, -20)
        
        //把按钮移到最顶层
        bringSubviewToFront(plusBtn)
    }
    
    //懒加载加号按钮
    lazy var plusBtn: UIButton = {
        
        let btn = UIButton()
    
    //设置背景图片
    btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
    
    btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
    
    //设置图片
    btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
    btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        return btn
    }()
}
